<template>
  <view class="section">
    <view class="title">
      {{ chapterName }}
    </view>
    <view class="container">
      <view class="content">
        <view class="content_top">
          <view class="text1">
            {{ wordText }}
          </view>
          <view class="text2">
            {{ wordSoundmark }}
          </view>
          <view class="text2"> 分音节：{{ disyllabic }} </view>
          <view class="text1">
            {{ wordParaphrase }}
          </view>
          <view class="button" @click="play()">
            <view class="button_content">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/horn.png"
                mode="widthFix"
              ></image>
            </view>
          </view>
        </view>
        <view class="content_bottom">
          <view class="box">
            <text>升学考试频次：{{ wordFrequency }}</text>
          </view>
          <slot name="memo"></slot>
        </view>
      </view>
      <view class="content">
        <view class="image">
          <image :src="wordImage" mode="widthFix"></image>
        </view>
        <view class="english">
          <view class="icon" @click="playExample()">
            <image
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/horn.png"
              mode="widthFix"
            ></image>
          </view>
          <view class="english_text">
            {{ exampleEnglish }}
          </view>
        </view>
        <view class="chinese">
          {{ exampleChinese }}
        </view>
      </view>
      <view class="content">
        <view class="content_box" v-if="!isRecord">
          <text class="content_title">单击麦克风并说出</text>
          <view class="content_image" @click="record()">
            <image
              class="img1"
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/voice.png"
              mode="widthFix"
            ></image>
          </view>
        </view>
        <view class="content_box" v-else-if="!isSuspend">
          <text class="content_title">
            正在录音 {{ minuteNumber }}:{{ secondNumber }}
          </text>
          <view class="content_image" @click="endRecord()">
            <image
              class="img2"
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/suspend.png"
              mode="widthFix"
            ></image>
          </view>
          <view class="record">
            <view class="record_text">
              {{ wordText }}
            </view>
            <RecordShape></RecordShape>
          </view>
        </view>
        <view class="content_box" v-else-if="isSuspend && !isHandle">
          <text class="content_title">处理中...</text>
          <view class="content_image">
            <image
              class="img3"
              src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/img/newimg/loading.png"
              mode="widthFix"
            ></image>
          </view>
        </view>
        <view class="content_section" v-else-if="isSuspend && isHandle">
          <view class="content_section_title" @click="playVoice()">
            <text>我的录音</text>
            <view class="content_section_image">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/play.png"
                mode="widthFix"
              ></image>
            </view>
          </view>
          <view class="score">
            <view class="score_text"> {{ score }}分 </view>
            <view class="score_text" v-if="isPass">
              过关
            </view>
            <view class="score_text" v-else>
              未过关
            </view>
          </view>
          <view class="record">
            <view class="record_text">
              {{ wordText }}
            </view>
            <view class="record_shape">
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
              <view></view>
            </view>
          </view>
          <view class="word">
            <view class="word_left">
              <text>标准发音</text>
              <text>音素匹配</text>
            </view>
            <view class="word_right" v-if="syllArray.length > 0">
              <view
                class="word_content"
                v-for="(item, index) in syllArray"
                :key="index"
              >
                <text class="word_text1">{{ item.content }}</text>
                <text class="word_text2">{{ item.score }}</text>
              </view>
            </view>
          </view>
          <view class="content_button">
            <view
              class="content_button_box"
              @click="practiceAgain()"
              v-if="!isPass && showAnswer"
            >
              <text>再次练习</text>
            </view>
            <view
              class="content_button_box"
              @click="nextQuestion()"
              v-if="isPass && showAnswer"
            >
              <text>下一题</text>
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/start_arrow.png"
                mode="widthFix"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </view>
    <Tips :show="showTips1" :content="tipsContent1"></Tips>
    <Tips :show="showTips2" :content="tipsContent2"></Tips>
  </view>
</template>

<script>
import { getRandomToDecimal } from "@/libs/tools";
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";
import dictList from "@/libs/PronunciationDict";

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;

const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;

export default {
  name: "LeadRead",
  props: {
    chapterData: {
      type: Object,
      default: null,
    },
    wordData: {
      type: Object,
      default: null,
    },
    isNeedRecord: {
      type: Boolean,
      default: false,
    },
  },
  created() {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function(res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
    this.initData();
  },
  mounted() {},
  data() {
    return {
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
      chapterName: "",
      wordInfo: null,
      wordText: "",
      wordSoundmark: "",
      disyllabic: "",
      wordParaphrase: "",
      wordImage: "",
      wordFrequency: "",
      wordAudio: "",
      exampleEnglish: "",
      exampleChinese: "",
      exampleAudio: "",
      syllArray: [],
      timerId: null,
      second: 0,
      minute: 0,
      secondNumber: "",
      minuteNumber: "",
      isRecord: false,
      isSuspend: false,
      isHandle: false,
      isRejected: "false",
      recorderCount: 0,
      passCount: 3,
      score: 0,
      passScore: 80,
      isPass: false,
      showAnswer: false,
      isCanClick: true,
      isCanNext: true,
      endFlag: false,
      hasGold: true,
      goldNum: 0,
      showTips1: false,
      showTips2: false,
      tipsContent1: "请不要乱读哦~",
      tipsContent2: "已连续三次未通过",
    };
  },
  methods: {
    initData() {
      this.chapterName = this.chapterData.shortName;
      this.wordText = this.wordData.word;
      this.wordParaphrase = this.wordData.wordParaphrase;
      this.wordImage = this.wordData.wordImage;
      this.wordSoundmark = this.wordData.wordSoundmark;
      this.disyllabic = this.wordData.disyllabic;
      this.wordFrequency = this.wordData.wordFrequency;
      this.wordAudio = this.wordData.wordAudio;
      if (this.wordData.sentence) {
        this.exampleEnglish = this.wordData.sentence.sentenceEnglish;
        this.exampleChinese = this.wordData.sentence.sentenceChinese;
        this.exampleAudio = this.wordData.sentence.sentenceAudio;
      }
      this.play();
    },
    initWord() {
      this.isRecord = false;
      this.isSuspend = false;
      this.isHandle = false;
      this.showAnswer = false;
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      setTimeout(() => {
        this.isCanClick = true;
      }, 1000);
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function(permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    saveWordRecord(score) {
      this.isCanNext = false;
      this.$emit("save", score);
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
      this.time();
      this.isRecord = true;
    },
    endRecord() {
      this.isSuspend = true;
      recorderManager.stop();
      clearInterval(this.timerId);
      this.second = 0;
      this.minute = 0;
    },
    playVoice() {
      if (!englishAudioContext.paused) return;
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.$upload(this.voicePath, { wordText: this.wordText }).then((res) => {
        let xml = res.data;
        let grade = parser.parse(xml, {
          attributeNamePrefix: "",
          ignoreAttributes: false,
        });
        if (grade) {
          let read_chapter =
            grade.xml_result.read_sentence.rec_paper.read_chapter;
          this.getSyllData(read_chapter);
          this.isRejected = read_chapter.is_rejected;
          if (this.isRejected === "true") {
            this.showTips1 = true;
            setTimeout(() => {
              this.showTips1 = false;
            }, 2000);
          }
          this.score = Number(read_chapter.total_score).toFixed(2);
          this.isPass = this.score >= this.passScore ? true : false;
          if (this.isPass) {
            this.saveWordRecord(this.score);
          } else {
            this.recorderCount++;
            if (!this.isNeedRecord) {
              if (this.recorderCount >= this.passCount) {
                this.isPass = true;
                if (this.recorderCount === this.passCount) {
                  this.showTips2 = true;
                  setTimeout(() => {
                    this.showTips2 = false;
                  }, 2000);
                  let start = 80;
                  let end = 100;
                  this.score = getRandomToDecimal(start, end);
                  this.saveWordRecord(this.score);
                }
              }
            } else {
              if (this.recorderCount >= this.passCount) {
                this.isPass = true;
                if (this.recorderCount === this.passCount) {
                  setTimeout(() => {
                    this.showTips2 = false;
                  }, 2000);
                  let start = 80;
                  let end = 100;
                  this.score = getRandomToDecimal(start, end);
                }
              }
              this.saveWordRecord(this.score);
            }
          }
          this.isHandle = true;
          this.showAnswer = true;
        }
      });
    },
    time() {
      this.timerId = setInterval(() => {
        this.second++;
        if (this.second > 59) {
          this.second = 0;
          this.minute++;
        }
        if (this.second < 10) {
          this.secondNumber = this.second.toString().padStart(2, "0");
        } else {
          this.secondNumber = this.second.toString();
        }
        if (this.minute < 10) {
          this.minuteNumber = this.minute.toString().padStart(2, "0");
        } else {
          this.minuteNumber = this.minute.toString();
        }
      }, 1000);
    },
    play() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.wordAudio;
      englishAudioContext.play();
    },
    playExample() {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.exampleAudio;
      englishAudioContext.play();
    },
    practiceAgain() {
      this.initWord();
    },
    nextQuestion() {
      if (!this.isCanNext) return;
      if (this.endFlag) {
        this.$emit("show", this.endFlag, this.hasGold, this.goldNum);
        return;
      }
      this.recorderCount = 0;
      this.initWord();
      this.$emit("change");
    },
    handleSaveData(endFlag, hasGold, goldNum) {
      this.endFlag = endFlag;
      this.hasGold = hasGold;
      this.goldNum = goldNum;
      this.isCanNext = true;
    },
    getSyllData(result) {
      let syllArray = [];
      let sentence = result.sentence;
      let anArray = [];
      if (!Array.isArray(sentence)) {
        anArray.push(sentence);
      } else {
        anArray = sentence;
      }
      anArray.forEach((item) => {
        let anWordArray = [];
        if (!Array.isArray(item.word)) {
          anWordArray.push(item.word);
        } else {
          anWordArray = item.word;
        }
        anWordArray.forEach((item) => {
          if (item.content === "fil" || item.content === "sil") return;
          let anSyllArray = [];
          if (!Array.isArray(item.syll)) {
            anSyllArray.push(item.syll);
          } else {
            anSyllArray = item.syll;
          }
          anSyllArray.forEach((item) => {
            let syll_score = Number(item.syll_score).toFixed(2);
            const nonStandard = item.content;
            const splitResult = nonStandard.split(" "); // 分割成 ["eh", "m"]
            const standardResult = splitResult
              .map((phoneme) => {
                const found = dictList.find(
                  (item) => item.nonstandard === phoneme
                );

                return found ? found.standard : phoneme; // 如果找到映射则替换，否则保持原样
              })
              .join(" ");
            let syll_content = standardResult;
            syllArray.push({
              content: syll_content,
              score: syll_score,
            });
          });
        });
      });
      this.syllArray = syllArray;
    },
  },
};
</script>
<style scoped lang="scss">
@import "./LeadRead";
</style>
